<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/10/30
 * Time: 13:13
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this,$base . '/app/css/vest-list.css');

AppAsset::addCss($this,$base . '/css/jquery.Jcrop.css');
AppAsset::addScript($this,$base . '/js/jquery.Jcrop.min.js');

AppAsset::addScript($this,$base . '/app/js/jedate.js');
AppAsset::addScript($this,$base . '/app/js/app-js.js');
AppAsset::addCss($this,$base . '/app/css/skin/jedate.css');

$model = new CommonHelper();
$baseUrlHead  = $model->getIp();

$tomorrowDate = $model->getTomorrowDateHI();
$yesterdayDate = $model->getYesterdayDateHI();
?>

<div class="search-box">
    <p class="datep" style="margin-left: 1.67rem;">
        <img src="<?=$base?>/app/images/new/rc_icon_date.png" class="date-icon">
        <input class="datainp" id="datebut" type="text" placeholder="请选择"  readonly>
    </p>

    <span class="date-split">至</span>

    <p class="datep">
        <img src="<?=$base?>/app/images/new/rc_icon_date.png" class="date-icon">
        <input class="datainp" id="datebut2" type="text" placeholder="请选择"  readonly>
    </p>

    <img id="search-img" onclick="searchFunction()" class="search-icon" style="margin-left: 1.67rem;" src="<?=$base?>/app/images/new/rc_btn_search_n.png">

    <select id="cityID" style="margin-left: 1.67rem;float: left;" onchange="searchFunction()">
        <option value="-1">所在城市</option>
        <option value="179">杭州市</option>
        <?php for($index=0;$index<count($cities);$index++){?>
            <option value="<?= $cities[$index]['city_code']?>"><?= $cities[$index]['city_name']?></option>
        <?php }?>
    </select>

    <div style="clear:both;"></div>

    <div class="dropdown" style="margin-left:1.67rem;font-size: 1.3rem;float: left">
        <button type="button" class="btn dropdown-toggle" id="dropdownMenu2"
                data-toggle="dropdown">
            举报状态
            <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">
            <li role="presentation" >
                <a role="menuitem" tabindex="-1" href="javascript:choosereportStatus('举报状态',-1)">请选择</a>
            </li>
            <li role="presentation" >
                <a role="menuitem" tabindex="-1" href="javascript:choosereportStatus('已处理',1)">已处理</a>
            </li>
            <li role="presentation" >
                <a role="menuitem" tabindex="-1" href="javascript:choosereportStatus('未处理',0)">未处理</a>
            </li>
        </ul>
    </div>

    <div class="dropdown" style="margin-left:1.67rem;font-size: 1.3rem;float: left">
        <button type="button" class="btn dropdown-toggle" id="dropdownMenu"
                data-toggle="dropdown">
            举报来源
            <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
            <li role="presentation" >
                <a role="menuitem" tabindex="-1" href="javascript:choosereportSource('举报来源',-1)">请选择</a>
            </li>
            <li role="presentation" >
                <a role="menuitem" tabindex="-1" href="javascript:choosereportSource('用户',1)">用户</a>
            </li>
            <li role="presentation" >
                <a role="menuitem" tabindex="-1" href="javascript:choosereportSource('动态',2)">动态</a>
            </li>
            <li role="presentation" >
                <a role="menuitem" tabindex="-1" href="javascript:choosereportSource('评论',3)">评论</a>
            </li>
        </ul>
    </div>

    <div style="clear:both;"></div>
</div>

<div class="table-box" style="background: none">
    <table id="table" style="background: #FFFFFF;"></table>
</div>

<script>
    //初始化事件控件的日期
    var tomorrowDate = '<?php echo $tomorrowDate?>';
    var yesterdayDate = '<?php echo $yesterdayDate?>';
    $("#datebut").val("2018-09-01 00:00");
    $("#datebut2").val(tomorrowDate);

    //初始化表格设置
    $('#table').bootstrapTable({
        toolbar: '#toolbar',        //工具按钮用哪个容器
        clickToSelect: true,//点击行即可选中单选/复选框
        singleSelect: false,//复选框只能选择一条记录
        search: false,//是否显示右上角的搜索框
        striped: true,      //是否显示行间隔色
        cache: false,            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sidePagination: "server", //服务端处理分页
        pagination: true,     //是否显示分页（*）
        sortable: false,           //是否启用排序
        sortOrder: "asc",          //排序方式
        method: 'GET',      //请求方式（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 10,      //每页的记录行数（*）
//        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        cardView: false,          //是否显示详细视图
        queryParams:setParams,
        uniqueId:'report_id',
        url:'report',
        responseHandler:dataProcess,
        columns: [{
            field: 'report_id',
            align: 'center',
            valign: 'middle',
            title: '举报ID'
        },{
            field: 'report_type',
            align: 'center',
            valign: 'middle',
            title: '举报来源',
            formatter:function(value,row, index) {
                console.log(row);
                if (row.report_type == 1) {
                    return "用户";
                } else if (row.report_type == 2) {
                    return "动态";
                } else {
                    return "评论";
                }
            }
        },{
            field: 'is_deleted',
            align: 'center',
            valign: 'middle',
            title: '状态',
            formatter:function(value, row, index) {
                if (row.is_deleted == 0) {
                    return "待处理";
                } else {
                    return "已处理";
                }
            }

        },{
            field: 'user.user_nickname',
            align: 'center',
            valign: 'middle',
            title: '举报者',
        },{
            field: 'user.city_name',
            align: 'center',
            valign: 'middle',
            title: '城市',
        },{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '操作',
            formatter:function(value,row,index) {
                if (row.report_type == 1) {
                    type = "用户";
                } else if (row.report_type == 2) {
                    type = "动态";
                } else {
                    type = "评论";
                }

                if (row.is_deleted == 0) {
                    return '<span style="color: #0000ff" onclick="reportDetails('+row.report_id+', '+ row.report_type +')"> 查看'+ type +' </span> | <span style="color: #0000ff" onclick="editStatus('+row.report_id+', 1)"> 设为已处理 </span>';
                } else {
                    return '<span style="color: #0000ff" onclick="reportDetails('+row.report_id+', '+ row.report_type +')"> 查看'+ type +' </span> | <span style="color: #0000ff" onclick="editStatus('+row.report_id+', 0)"> 设为未处理 </span>';
                }
            }
        }]
    });

    function dataProcess(res){
        var data = res;
        return {
            'rows':data.rows,
            'total':data.total
        }
    }

    var reportType = -1;
    var reportStatus = -1;

    function setParams(params){
        var start_date = $('#datebut').val(); //按日期搜索
        var end_date = $('#datebut2').val();

        if (start_date == "2018-09-01 00:00") {
            var start_date = undefined; //按日期搜索
            var end_date = undefined;
        }

        if (start_date && start_date != undefined && end_date && end_date != undefined){
            params.start_date = start_date;
            params.end_date = end_date;
        }

        var cityCode = $("#cityID").val();
        if(cityCode != -1)
            params.city_code = cityCode;

        if (reportType != -1)
            params.report_type = reportType;

        if (reportStatus != -1)
            params.report_state = reportStatus;

        var content = $("#nameId").val();
        if (content && content != undefined && content.length > 0)
            params.user_name = content;

        return params;
    }

    function choosereportSource(name,type){
        reportType = type;
        $("#dropdownMenu").text(name);
        $('#table').bootstrapTable('refreshOptions', {pageNumber: 1});
    }

    function choosereportStatus(name,status){
        reportStatus = status;
        $("#dropdownMenu2").text(name);
        $('#table').bootstrapTable('refreshOptions', {pageNumber: 1});
    }

    function searchFunction(){
        $('#table').bootstrapTable('refreshOptions', {pageNumber: 1});
    }

    function showDialog(){
        $(".dialog-topic").show();
    }

    function hideDialog(){
        $(".dialog-topic").hide();
    }

    var createVestController = {
        createVestApi:'<?= $baseUrlHead?>Hotcity/v1/users',
        createVestFunc : function(){

            var mobile = "168168" + Math.round(new Date().getTime()/1000).toString();

            var userAvatar = $("#img").attr("src");
            if(userAvatar.indexOf("http") == -1){
                alert("请上传头像");
                return;
            }

            var userName = $("#vestName").val();
            if(userName.length == 0){
                alert("请输入昵称");
                return;
            }

            var userAge = $("#vestAge").val();
            if(userAge.length == 0){
                alert("请输入年龄");
                return;
            }

            var userSex = $("#sexID").val();

            var cityCode = $("#cityID").val();

            var param = {
                mobile:mobile,
                user_avatar: userAvatar,
                user_nickname:userName,
                user_age:parseInt(userAge).toString(),
                user_lng:"120",
                user_lat:"30",
                user_sex:userSex,
                city_code:cityCode
            };

            $(".loading-area").show();
            sendAjax(this.createVestApi,"POST",param,false,function(res){
               if(res.code != 0){
                   location.reload();
               }else
                   alert(res.msg);
            });
        }
    }

    function goToDetail(user_id, menuitemid){
        window.open("vest-detail?user_id="+user_id+"&menuitemid="+menuitemid);
    }

    // ajax修改举报状态
    function editStatus(report_id, is_deleted){
        report = "report";
        if (confirm('确认修改该状态？')) {
            var param = {
                'report_id' : report_id,
                'is_deleted' : is_deleted
            };

            sendAjax(this.report,"POST",param,false,function(res){
                if(res.code != 0){
                    $('#table').bootstrapTable('refresh');

                }else {
                    alert(res);
                }
            });
        }
    }

    function goToProhibition(report_id) {
        window.open("report?report_id="+report_id);
    }

</script>

<script>
    $(function(){
//选择图片点击事件
        $(".myClose").click(function(){
            closePic();
        });
        $(".select-img").click(function(){
            upload(this);
        });
        $(".upload-img").click(function(){
            uploadImage(this);
        });
        //选择图片结束
    });

    //点击图片来选择上传的图片
    function upload(button){
//        $(button).css('background-color','#77778F').css('color','white');
        var intputId = 'upload-file2';
        document.getElementById(intputId).click();
    }

    function showPic(){
        $('.choose-area').show();
    }

    function closePic(){
        $('.choose-area').hide();
        $('.pic-area').empty();
        if (!$('.pic-area img').length){
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        $('.upload').css('background-color','white').css('color','#A8A8A8');
        $('.select-img').css('background-color','white').css('color','#A8A8A8');
        //清除input file 的value,可以触发下次的onchange;
        $('#upload-file2').val('');

        $('.upload-img').css('background','white').prop('disabled',false);

    }
    //选择图片之后的操作

    //图片缩略图处理
    function thumbImage(input){
        //设置宽高比
        var w = 1;
        var h = 1;

        //再次点击上传时清除之前的截图操作
        if ($('.jcrop-holder').length){
            $('.pic-area').empty();
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        if (typeof (FileReader) != "undefined") {
            var regex = /(.jpg|.jpeg|.png)$/;
            $($(input)[0].files).each(function () {
                var file = $(this);
                if (regex.test(file[0].name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
//                        var img = $(input).prev();
                        var img = $('#pic-area-img');
                        $(img).attr('src',e.target.result);
                        var realWidth;//真实的宽度
                        var realHeight;//真实的高度
                        //这里做下说明，$("<img/>")这里是创建一个临时的img标签，类似js创建一个new Image()对象！
                        $("<img/>").attr("src", $(img).attr('src')).load(function() {
                            /*
                             如果要获取图片的真实的宽度和高度有三点必须注意
                             1、需要创建一个image对象：如这里的$("<img/>")
                             2、指定图片的src路径
                             3、一定要在图片加载完成后执行如.load()函数里执行
                             */
                            realWidth = this.width;
                            realHeight = this.height;
                            var width = $('.pic-area').css('width').split('p')[0];
                            var height = $('.pic-area').css('height').split('p')[0];
//                            console.log(realWidth,realHeight,width,height)
                            if(realWidth<width && realHeight<height){
                                $(img).css("width",realWidth+'px').css("height",realHeight+'px');
                            }else{
                                //如果真实的宽高比大于给定的宽高比就按照宽度100%显示
                                if(realWidth/realHeight >= width/height){
                                    $(img).css("width","99%").css("height","auto");
                                }
                                else{//如果小于给定的宽高比按照原尺寸显示
                                    $(img).css("width","auto").css("height","99%");
                                }
                            }
//                            console.log(realWidth,$(img).css("width").split('p')[0]);
                            var ratio = realWidth/$(img).css("width").split('p')[0];
//                            console.log(ratio)
                            $('#pic-area-img').show();
                            var jcrop_api;
                            $('#pic-area-img').Jcrop({
                                aspectRatio: w / h,
                                onSelect:uodateCoords,
                                setSelect:[0,0,600,600]
                            },function(){
                                jcrop_api = this;
                            });
                            function uodateCoords(c){
                                $('#x').val(c.x*ratio);
                                $('#y').val(c.y*ratio);
                                $('#w').val(c.w*ratio);
                                $('#h').val(c.h*ratio);
                            }
                            var jcropWidth =   $(img).css('width').split('p')[0];
                            var jcropHeight =   $(img).css('height').split('p')[0];
                            var marginLeft = (width-jcropWidth)/2;
                            var marginTop = (height-jcropHeight)/2;
//                            $('.jcrop-holder').css("margin-top",marginTop + 'px');
                            $('.jcrop-holder').css("margin-left",marginLeft + 'px');
//                            jcrop_api.setSelect([marginLeft,marginTop,336,336]);
                        });
                    }
                    reader.readAsDataURL(file[0]);
                }else {
                    alert(file[0].name + " is not a valid image file.");
                    return false;
                }
            })
        }else{
            alert("This browser does not support HTML5 FileReader.");
        }
    }
    //ajax 异步上传图片
    function uploadImage(button){
        //定义允许上传的图片格式 在前台就可以直接判断，不合法的格式将不会上传
        //尺寸限制

        var intputId = 'upload-file2';
        var limit = 8 * 1024 * 1024;

        var file = $('#'+intputId).get(0).files;

//            $($(button).parent().prev().children()[1]).get(0).files;
        var filetype = ['jpg','jpeg','png','gif'];
        if(file.length){
            var fi = file[0]; //得到文件信息
            //判断文件格式是否是图片 如果不是图片则返回false
            var index = fi.name.lastIndexOf('.');
            var fname = [fi.name.substring(0,index),fi.name.substring(index+1)];
            if(filetype.indexOf(fname[1].toLowerCase()) == -1){
                alert('文件格式不支持');
                return ;
            }
            //实例化h5的fileReader
            var fr = new FileReader();
            fr.readAsDataURL(fi); //以base64编码格式读取图片文件
            fr.onload = function(frev){
                pic = frev.target.result; //得到结果数据
                //开始上传之前，预览图片
//                $('#img').attr('src',pic);
                //使用ajax 利用post方式提交数据
                var x = $('#x').val();
                var y= $('#y').val();
                var width= $('#w').val();
                var height= $('#h').val();
                if (width == 0 && height == 0){
                    alert('请选择图片');
                    return;
                }
                if(fi.size > limit){
                    alert("上传照片不得大于8M");
                    return;
                }
                $('.loading-area').show();
                $(button).css('background','#CCCCCC').prop('disabled',true);
                $.post(
                    'img-upload',
                    {
                        message:pic,
                        filename:fname[0],
                        filetype:fname[1].toLowerCase(),
                        filesize:fi.size,
                        x:x,
                        y:y,
                        width:width,
                        height:height,
                        limit:limit
                    },
                    function(data){
                        data = eval('('+data+')');
                        if(data.code == 1){
                            $('.loading-area').hide();
                            alert('上传失败');
                        }else if(data.code == 0){

                            $("#img").attr("src",data.imgSrc);

                            $('.loading-area').hide();
                            alert('上传成功');
                            closePic();
                        }else if(data.code == 2){
                            var size = parseInt(parseInt(data.size)/1000);
                            if (size>1000)
                                size = parseInt(size/1000) + 'M';
                            else
                                size += 'KB';
                            var msg = data.msg + ',当前图片尺寸为:' + size;
                            $('.loading-area').hide();
                            alert(msg);
                        }
                    }
                )
                    .fail(function(xhr,status,error){
//                    console.log(xhr,status,error)
                        $('.loading-area').hide();
                        alert('上传失败')
                    })
            }
        }else
            alert('请选择图片');
    }

    function reportDetails($reportId, type) {
        if (type != 1) {
            window.open("report-details?report_id="+$reportId+"&report_type="+type);
        }
    }
</script>